// pages/register/index.js
var _this, js;
import Toast from '../../../../../miniprogram_npm/@vant/weapp/toast/toast';
import * as Storage from '../../../../../utils/storage';
const $api = require('../../../../../request/api').API;

Page({
  /**
   * 页面的初始数据
   */
  data: {
    phone: '',
    code: '',
    second: 0,
    hc: '',
    agreement: false,
    showNicknameAvatarPopup: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (options.phone) {
      this.setData({
        phone: options.phone
      });
    }
  },
  clickAgreement() {
    if (this.data.agreement) return;
    this.setData({
      agreement: true
    });

    this.getcode();
  },
  clickAgreementText() {
    this.setData({
      agreement: true
    });
    wx.navigateTo({
      url: '/pages/login/customerAgreement/index'
    });
  },

  clear() {
    clearInterval(js);
    js = null;
    this.setData({
      second: 0
    });
  },
  getcode() {
    var _this = this;
    if (_this.data.phone.length != 11) {
      wx.showToast({
        icon: 'none',
        title: '手机号不正确'
      });
      return;
    }
    if (_this.data.second > 0) {
      return;
    }
    let params = {
      mobile: this.data.phone,
      smsType: 101
    };
    $api.getPhoneCode(params).then(res => {
      console.log('获取验证码的回调', res);
      if (res.data.status == 0) {
        wx.showToast({
          title: '发送验证码成功',
          status: 'success'
        });

        _this.setData({
          second: 60
        });
        js = setInterval(function () {
          _this.setData({
            second: _this.data.second - 1
          });
          if (_this.data.second == 0) {
            _this.clear();
          }
        }, 1000);
      }
    });
  },
  // 注册校验
  bindLogin() {
    if (this.data.agreement == false) {
      wx.showToast({
        icon: 'none',
        title: '请先阅读用户服务协议'
      });
      return;
    }
    if (this.data.phone.length != 11) {
      wx.showToast({
        icon: 'none',
        title: '手机号不正确'
      });
      return;
    }
    if (this.data.code.length == 0) {
      wx.showToast({
        icon: 'none',
        title: '请输入验证码'
      });
      return;
    }

    // 这个接口判断用户是否有填写过昵称，如果没有就需要去填写，注册不需要调用
    // let params = {
    //   openId: wx.getStorageSync(Storage.USER_OPEN_ID),
    //   userRole: 2,
    // }
    // $api.getNickName(params).then(res=>{
    //   let nickName = res.data.data
    //   if(nickName){
    //     this.login({
    //       nickName,
    //     })
    //   }else{
    this.setData({
      showNicknameAvatarPopup: true
    });
    //   }

    // })

    return;
    // 让用户授权获取头像和昵称，不授权就不让进首页
    wx.getUserProfile({
      desc: '登录', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: res => {
        Toast.loading({
          message: '加载中...',
          forbidClick: true
        });
        wx.setStorageSync('nickName', res.userInfo.nickName);
        wx.setStorageSync('avatarUrl', res.userInfo.avatarUrl);
        let params = {
          linkPhone: this.data.phone,
          yzm: this.data.code,
          openId: wx.getStorageSync(Storage.USER_OPEN_ID),
          nickName: res.userInfo.nickName
        };
        $api.customerRegister(params).then(res => {
          console.log('注册的回调', res);
          Toast.clear();
          if (res.data.status == 0) {
            // 写入token直接进入首页
            var userCode = res.data.data.userCode;
            var userRole = res.data.data.userRole;
            wx.setStorageSync(Storage.USER_ROLE, userRole);
            wx.setStorageSync(Storage.ACCESS_TOKEN, userCode);
            wx.showToast({
              title: '注册成功！',
              status: 'success'
            });
            // 先判断是否有呼叫器Code,有就说明是扫码进小程序的
            let code = wx.getStorageSync('beeperCode');
            if (code) {
              wx.setStorageSync('islogin', 'yes');
              let EquipmentType = wx.getStorageSync('EquipmentType');
              if (EquipmentType) {
                // 绑定安全设备页
                wx.reLaunch({
                  url: '/subcontract/equipment/pages/bindingEquipment/index'
                });
              } else {
                // 绑定呼叫器页
                wx.reLaunch({
                  url: '/subcontract/equipment/pages/bindingBeeper/index'
                });
              }
            } else {
              setTimeout(() => {
                wx.switchTab({
                  url: '/pages/equipment/index'
                });
              }, 1000);
            }
          }
        });
      }
    });
  },
  // 登录
  login(val) {
    let params = {
      linkPhone: this.data.phone,
      yzm: this.data.code,
      openId: wx.getStorageSync(Storage.USER_OPEN_ID),
      nickName: val.detail.nickName,
      image: val.detail.avatarBase
    };
    $api.customerRegister(params).then(res => {
      console.log('注册的回调', res);
      Toast.clear();
      if (res.data.status == 0) {
        // 写入token直接进入首页
        var userCode = res.data.data.userCode;
        var userRole = res.data.data.userRole;
        wx.setStorageSync(Storage.USER_ROLE, userRole);
        wx.setStorageSync(Storage.ACCESS_TOKEN, userCode);
        wx.setStorageSync('avatarUrl', res.data.data.imageUrl);
        wx.setStorageSync('nickName', res.data.data.nickName);
        wx.showToast({
          title: '注册成功！',
          status: 'success'
        });
        // 先判断是否有呼叫器Code,有就说明是扫码进小程序的
        let code = wx.getStorageSync('beeperCode');
        if (code) {
          wx.setStorageSync('islogin', 'yes');
          let EquipmentType = wx.getStorageSync('EquipmentType');
          if (EquipmentType) {
            // 绑定安全设备页
            wx.reLaunch({
              url: '/subcontract/equipment/pages/bindingEquipment/index'
            });
          } else {
            // 绑定呼叫器页
            wx.reLaunch({
              url: '/subcontract/equipment/pages/bindingBeeper/index'
            });
          }
        } else {
          setTimeout(() => {
            wx.switchTab({
              url: '/pages/equipment/index'
            });
          }, 1000);
        }
      }
    });
  },

  // 点击获取手机号
  getPhoneNumber(e) {
    console.log(e.detail.code);
    let cond = {
      code: e.detail.code,
      appId: Storage.APPID
    };
    $api.getPhone(cond).then(res => {
      this.setData({
        phone: res.data.data
      });
    });
  },

  // 跳转页面
  jumpPage(e) {
    let value = e.currentTarget.dataset.go;
    console.log(value);
    if (value == 'log') {
      wx.navigateTo({
        url: '/subcontract/person/pages/login/login/index'
      });
    } else if (value == 'forget') {
      wx.navigateTo({
        url: '/subcontract/person/pages/login/forget/index'
      });
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    this.clear();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
  // 输入框绑定值
  phoneInput(e) {
    let value = e.detail.value;
    this.setData({
      phone: value
    });
  },
  codeInput(e) {
    let value = e.detail.value;
    this.setData({
      code: value
    });
  }
});
